<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width="500"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '变更代理商' : '新建代理商'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      layout="horizontal"
      ref="form"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 19 }, sm: { span: 24 } }"
    >

      <a-form-item label="代理商:" name="agentId">
        <a-select
          placeholder="请选择代理商"
          v-model:value="form.agentId"
          show-search
          @change="reloadUser"
          allow-clear>
          <a-select-option v-for="item in agentList" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="客户负责人角色" name="roleId">
        <a-radio-group default-value="1780314166642053121"
                       v-model:value="form.roleId"
                       @change="reloadUser"
                       button-style="solid">
          <a-radio-button value="1780314166642053121">经理</a-radio-button>
          <a-radio-button value="1780314237760671746">员工</a-radio-button>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="客户负责人:" name="createUser">
        <a-select
          placeholder="选择客户负责人"
          v-model:value="form.createUser"
          show-search
          allow-clear>
          <a-select-option v-for="item in agentUserList" :key="item.userId" :value="item.userId">
            {{ item.realName }}
          </a-select-option>
        </a-select>
      </a-form-item>


    </a-form>
  </a-modal>
</template>

<script>
import { onMounted, ref } from 'vue';
import { AgentApi } from '@/api/AgentApi';
import { CustomerApi } from '@/api/CustomerApi';
import { WebUserApi } from '@/api/WebUserApi';

export default {
  name: 'AgentAccountEdit',
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  setup() {

    // 加载代理商下拉数据
    const agentList = ref([]);

    async function fetchAgentList() {
      const res = await AgentApi.findList({});
      agentList.value = res.data;
    }


    // 页面初次挂载时加载下拉数据
    onMounted(async () => {
      await fetchAgentList();
    });

    return {
      agentList
    };
  },
  data() {

    // 加载代理商员工数据
    let agentUserList;
    return {
      agentUserList,
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {
        agentId: [{ required: true, message: '请选择代理商', type: 'string', trigger: 'blur' }],
        createUser: [{ required: true, message: '请选择客户负责人', type: 'string', trigger: 'blur' }]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false

    };
  },

  watch: {
    data() {
      if (this.data) {
        // 编辑的时候适配组件数据类型
        this.form = Object.assign({}, this.data);
        this.isUpdate = true;
        this.getAgentUserList();
      } else {
        // 新增-清除表格内容
        this.form = {};
        this.isUpdate = false;
      }
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    visible() {
      // 清空表单校验信息
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
  },
  methods: {
    // 加载代理商员工列表
    async getAgentUserList() {
      const res = await WebUserApi.getAgentUserListByRoleId({ agentId: this.form.agentId, createUserRoleId: this.form.roleId });
      this.agentUserList = res.data;
    },

    // 重新加载代理商员工
    async reloadUser() {
      this.getAgentUserList();
      this.form.createUser = '';
    },

    /**
     * 保存和编辑
     */
    async save() {
      // 校验表单
      await this.$refs.form.validate();

      // 修改加载框为正在加载
      this.loading = true;

      let result = null;

      // 执行编辑或修改
      if (this.isUpdate) {
        const id = this.form.id;
        const agentId = this.form.agentId;
        const createUser = this.form.createUser;
        result = CustomerApi.edit({ id, agentId, createUser });
      } else {
        result = CustomerApi.add(this.form);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          this.$message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 更新编辑界面的弹框是否显示
     * @param value true-显示，false-隐藏
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }

  }
};
</script>

<style scoped>
</style>
